<?php
namespace Controller\Admin\Develop;

use Service\Auth\RoleService;
use Service\Develop\AutoDevModuleService;

/**
 * @node_name 自动化模块开发
 * Desc: 功能描述
 * Created by PhpStorm.
 * User: xuanskyer | <furthestworld@icloud.com>
 * Date: 2016-7-18 14:35:59
 */
use Service\Common\CodeCloneService;
class AutoDevModule extends \Controller\Admin\Common\Common {

    const SEPARATOR = '/';
    protected $defaultService;      //默认服务类
    protected $cloneCodeService;
    protected $roleService;

    public function __construct() {
        parent::__construct();
        $this->setHeaderFooter();
        $this->defaultService = new AutoDevModuleService();
        $this->cloneCodeService = new CodeCloneService();
        $this->roleService = new RoleService();

    }

    /**
     * @node_name 入口方法
     */
    public function index() {
        $actions = $this->buildUrl([
                                       'getDataList',
                                       'addData',
                                       'batchAddData',
                                       'editData',
                                       'deleteData',
                                       'batchDeleteData',
                                       'changeStatus',
                                       'autoCreateModule',
                                   ]);

        $this->view->assign('actions', $actions);
        $params                = $this->req;
        $field_maps            = $this->defaultService->getFieldMaps();
        $params['fields_list'] = $field_maps['fields_list'];
        $this->view->assign('params', $params);
        $class_name_arr = explode('\\', __CLASS__);
        array_shift($class_name_arr);
        $this->view->display(implode(self::SEPARATOR, $class_name_arr) . self::SEPARATOR . __FUNCTION__ . ".html");
    }

    /**
     * @node_name 查询数据列表
     */
    protected function getDataList() {
        $params = $this->parseJplistStatuses($this->req['statuses']);
        $result = $this->defaultService->getDataList($params);

        $this->ajaxReturn($result);
    }

    /**
     * @node_name 自动创建模块
     */
    public function autoCreateModule() {
        if (IS_GET) {
            $role_list = $this->roleService->getRoleListByWhere([]);
            $module_list = $this->defaultService->getModuleList([
                                                                    '.', '..', 'Common'
                                                                ]);

            $actions = $this->buildUrl([
                                           'getTableFields',
                                       ]);

            $ret = ['status' => 1, 'info' => 'ok', 'data' => [
                'module_list' => $module_list,
                'role_list' => array_values($role_list),
                'actions' => $actions
            ]];
            $this->ajaxReturn($ret);
        } else {

            $table_fields = $this->post['model']['dna_table_fields'];
            $field_list = [];
            if(!empty($table_fields) && is_array($table_fields)){
                foreach($table_fields as $one){
                    array_push($field_list, unserialize(base64_decode($one)));
                }
            }
            $this->post['model']['dna_table_fields'] = $field_list;
            $res = $this->checkCreateParams($this->post);
            if (1 == $res['status']) {
                $res = $this->cloneCodeService->createModule($res['data']);
            }
            $this->ajaxReturn($res);
        }

    }

    private function checkCreateParams($params = []) {

        if (!isset($params['module']['dna_module_dir']) || empty($params['module']['dna_module_dir'])) {
            return ['status' => 0, 'info' => '请设置模块所属目录'];
        }elseif(!empty(preg_replace('/[a-zA-Z]/', '', $params['module']['dna_module_dir']))){
            return ['status' => 0, 'info' => '模块所属目录必须为纯字母'];
        }else{
            $params['module']['dna_module_dir'] = ucfirst($params['module']['dna_module_dir']);
        }

        if (!isset($params['module']['dna_module_name']) || empty($params['module']['dna_module_name'])) {
            return ['status' => 0, 'info' => '请设置模块名称'];
        }elseif(!empty(preg_replace('/[a-zA-Z]/', '', $params['module']['dna_module_name']))){
            return ['status' => 0, 'info' => '模块名称必须为纯字母'];
        }else{
            $params['module']['dna_module_name'] = ucfirst($params['module']['dna_module_name']);
        }

        if (!isset($params['model']['dna_class_name']) || empty($params['model']['dna_class_name'])) {
            return ['status' => 0, 'info' => '请设置模型名称'];
        }elseif(!empty(preg_replace('/[a-zA-Z]/', '', $params['model']['dna_class_name']))){
            return ['status' => 0, 'info' => '模型名称必须为纯字母'];
        }else{
            $params['model']['dna_class_name'] = ucfirst($params['model']['dna_class_name']);
        }

        if (!isset($params['model']['dna_table_name']) || empty($params['model']['dna_table_name'])) {
            $model_class_name = str_replace(['model', 'Model'], ['', ''], $params['model']['dna_class_name']);
            $params['model']['dna_table_name'] = preg_replace_callback('/[A-Z]/', function($matches){
                return '_'.strtolower($matches[0]);
            }, lcfirst($model_class_name));
        }
        if (!isset($params['model']['dna_table_fields']) || empty($params['model']['dna_table_fields'])) {
            $res = $this->defaultService->getTableFields(['name' => $params['model']['dna_table_name']]);
            if(1 == $res['status']){
                $params['model']['dna_table_fields'] = $res['data'];
            }
        }

        if (!isset($params['service']['dna_class_name']) || empty($params['service']['dna_class_name'])) {
            return ['status' => 0, 'info' => '请设置服务类名'];
        }elseif(!empty(preg_replace('/[a-zA-Z]/', '', $params['service']['dna_class_name']))){
            return ['status' => 0, 'info' => '服务类名必须为纯字母'];
        }else{
            $params['service']['dna_class_name'] = ucfirst($params['service']['dna_class_name']);
        }
        $data['role'] = $params['role'];
        $data['module'] = $params['module'];
        $model_name = str_replace(['model', 'Model'], ['',''], $params['model']['dna_class_name']) . 'Model';
        $params_model    = [
            'file_name'    => "Model/{$model_name}.php",
            'replace_data' => [
                'dna_namespace'  => "Model" . "\\" . $params['module']['dna_module_dir'],
                'dna_class_name' => $model_name,
                'dna_db_name' => $params['model']['dna_db_name'],
                'dna_table_name' => $params['model']['dna_table_name'],
                'dna_table_fields' => $params['model']['dna_table_fields'],
                'dna_table_fields_show' => $params['model']['dna_table_fields_show']
            ]
        ];
        $data['model'] = $params_model;

        $service_name = str_replace(['service', 'Service'], ['',''], $params['service']['dna_class_name']) . 'Service';
        $params_service    = [
            'file_name'    => "Service/{$service_name}.php",
            'replace_data' => [
                'dna_namespace'  => "Service" . "\\" . $params['module']['dna_module_dir'],
                'dna_class_name' => $service_name,
                'dns_model_name' => isset($params['service']['dna_model_name']) && !empty($params['service']['dna_model_name'])
                    ? $params['service']['dna_model_name']
                    : $model_name,
            ]
        ];
        $data['service'] = $params_service;
        $params_controller    = [
            'file_name'    => "Controller/{$params['module']['dna_module_name']}.php",
            'replace_data' => [
                'dna_doc_title' => isset($params['module']['dna_doc_title']) && !empty($params['module']['dna_doc_title']) ? $params['module']['dna_doc_title'] : '自动化模块创建名称',
                'dna_namespace'    => "Controller\\Admin" . "\\" . $params['module']['dna_module_dir'],
                'dna_class_name'   => $params['module']['dna_module_name'],
                'dna_service_name' => $service_name,
                'dna_use'          => "Service". "\\". $params['module']['dna_module_dir'] . "\\". $service_name,
            ]
        ];
        $data['controller'] = $params_controller;
        $params_view      = [
            'dna_view_dir' => "View/{$params['module']['dna_module_dir']}/{$params['module']['dna_module_name']}",
            'copy_file'    => [
                'addData.html',
                'editData.html',
                'index.html'
            ]
        ];
        $data['view']   = $params_view;
        $lower_module_dir = strtolower($params['module']['dna_module_dir']);
        $lower_module_name = strtolower($params['module']['dna_module_name']);
        $data['router'] = [
            'route_file'   => 'Conf/router.conf',
            'replace_data' => [
                'route_desc'          => !empty($params['module']['dna_doc_title']) ? $params['module']['dna_doc_title'] : '自动化创建模块路由',
                'dna_static'          => "{$lower_module_dir}/{$lower_module_name}",
                'dna_controller_path' => $params['module']['dna_module_dir'] . "\\" . $params['module']['dna_module_name'],
            ]
        ];

        $ret = ['status' => 1, 'info' => 'ok', 'data' => $data];

        return $ret;
    }

    /**
     * @node_name 新增
     */
    public function addData() {
        if (IS_GET) {
            $params                = [];
            $actions               = $this->buildUrl([

                                                     ]);
            $field_maps            = $this->defaultService->getFieldMaps();
            $params['fields_maps'] = $field_maps;
            $this->view->assign('params', $params);
            $this->view->assign('fields_add', json_encode($field_maps['fields_add']));
            $this->view->assign('actions', $actions);
            $class_name_arr = explode('\\', __CLASS__);
            array_shift($class_name_arr);
            $this->view->display(implode(self::SEPARATOR, $class_name_arr) . self::SEPARATOR . __FUNCTION__ . ".html");
        } else {
            $res = $this->defaultService->addData($this->post);
            $this->ajaxReturn($res);
        }
    }

    /**
     * @node_name 批量新增
     */
    public function batchAddData() {

    }

    /**
     * @node_name 批量删除
     */
    public function batchDeleteData() {

    }

    /**
     * @node_name 编辑
     */
    public function editData() {
        if (IS_GET) {
            $where = [
                'id' => $this->get['id']
            ];
            $this->view->assign('params', $this->req);
            $data       = $this->defaultService->getDataInfo($where);
            $field_maps = $this->defaultService->getFieldMaps();
            foreach ($field_maps['fields_edit'] as $key => $val) {
                if (isset($val['form_config']['name']) &&
                    !empty($val['form_config']['name']) && isset($data[$val['form_config']['name']])
                ) {
                    $field_maps['fields_edit'][$key]['form_config']['value'] = $data[$val['form_config']['name']];
                }
            }
            $this->view->assign('fields_edit', json_encode($field_maps['fields_edit']));

            $actions = $this->buildUrl([

                                       ]);
            $this->view->assign('actions', $actions);
            $class_name_arr = explode('\\', __CLASS__);
            array_shift($class_name_arr);
            $this->view->display(implode(self::SEPARATOR, $class_name_arr) . self::SEPARATOR . __FUNCTION__ . ".html");

        } else {
            $res = $this->defaultService->editData($this->post);

            $this->ajaxReturn($res);
        }
    }

    /**
     * @node_name 删除
     */
    public function deleteData() {
        $id           = $this->req['id'];
        $list         = $this->defaultService->getDataList(['where' => ['id' => $id]]);
        $profile_info = [];
        if (isset($list['data']) && !empty($list['data'])) {
            $profile_info = array_pop($list['data']);
        }
        if (empty($profile_info)) {
            $this->ajaxReturn(['status' => 0, 'info' => '记录不存在']);
        }
        $res = $this->defaultService->deleteDataById($id);

        $this->ajaxReturn($res);
    }

    /**
     * @node_name 修改审核状态
     */
    public function changeStatus() {
        if (!isset($this->post['id'])) {
            $this->ajaxReturn(['status' => 0, 'info' => '请指定要修改的记录']);
        }

        $list         = $this->defaultService->getDataList(['where' => ['id' => $this->post['id']]]);
        $profile_info = [];
        if (isset($list['data']) && !empty($list['data'])) {
            $profile_info = array_pop($list['data']);
        }
        if (empty($profile_info)) {
            $this->ajaxReturn(['status' => 0, 'info' => '记录不存在']);
        }

        if (!isset($this->post['status'])) {
            $this->ajaxReturn(['status' => 0, 'info' => '未设置审核状态']);
        }
        $update_data = [
            'id'         => $this->post['id'],
            'status' => intval($this->post['status'])
        ];
        $res         = $this->defaultService->changeStatus($update_data);

        $this->ajaxReturn($res);
    }

    /**
     * @node_name 获取数据表字段
     */
    public function getTableFields(){
        $res = $this->defaultService->getTableFields($this->req);
        $this->ajaxReturn($res);
    }
}